using System;
using System.Collections;
using System.Collections.Generic;
using System.Numerics;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using static UnityEditor.Progress;

public class InventoryController : MonoBehaviour
{
    //[HideInInspector]
    public ItemGrid selectedItemGrid;
    public ItemGrid SelectedItemGrid { 
        get => selectedItemGrid;
        set {
            selectedItemGrid = value;
            inventoryHeightLight.setParent(value);
            InventoryInFind.setParent(value);
        } }
    
    public InventoryItem selectedItem;
    InventoryItem overlapItem;
    RectTransform rectTransform;
    [SerializeField]List<ItemData> itemDatas;
    [SerializeField]GameObject itemPrefab;
    [SerializeField]Transform canvasTransForm;

    Vector2Int oldPosition;
    InventhightLight inventoryHeightLight;
    InventoryInFind InventoryInFind;
    public ItemGrid findGrid;
    InventoryItem findItem;


    private void Awake()
    {
        inventoryHeightLight = GetComponent<InventhightLight>();
        InventoryInFind = GetComponent<InventoryInFind>();
    }
    private void Update()
    {

        //if (Input.GetKeyDown(KeyCode.Q)) {
        //    if (selectedItem == null ) {
        //        CreateRandomItem();
        //    }

        //}
        //iconDrog();
        //if (Input.GetKeyDown(KeyCode.Q)) {
        //    selectedItem.Rotate();
        //}
            if (selectedItemGrid != null)
        {
            handleHightLight();
        }
        else {
            inventoryHeightLight.show(false);
        }

        totalRandomItem();

        //RotateItem();


        //if (Input.GetMouseButtonDown(0))
        //{
        //    leftButtonPress();
        //}

    }

    //private void RotateItem()
    //{
        
    //    if (selectedItem == null || selectedItemGrid == null) { return; }
    //    Vector2Int tileGridPostion = GetTileGridPosition();
    //    bool needRotate=selectedItemGrid.NeedRotate(selectedItem, tileGridPostion.x, tileGridPostion.y);
    //    if (needRotate) {
    //        selectedItem.Rotate();
    //    }
        
    //}

    //private void InserRandomItem()
    //{
    //    if (selectedItemGrid == null) { return; }

    //    CreateRandomItem();
    //    InventoryItem itemInsert = selectedItem;
    //    selectedItem = null;
    //    InsertItem(itemInsert);
    //}

    private void totalRandomItem()
    {
        if (findGrid == null) { return; }
        if (!findGrid.isOpen) {
            int ItemNum = UnityEngine.Random.Range(7, 15);
            for (int i = 0; i < ItemNum; i++)
            {
                CreateRandomItem();
                InventoryItem itemInsert = findItem;
                findItem = null;
                InsertItem(itemInsert);
                if (itemInsert != null) {
                    itemInsert.setIsHide(true);
                    findGrid.backpackTotalItem.Add(itemInsert);
                }
                
            }
            findGrid.isOpen = true;

            StartCoroutine(openItem());


        }
       
        
    }

    IEnumerator openItem() {
        List<InventoryItem> backpackTotalItem = findGrid.backpackTotalItem;
        foreach (InventoryItem item in backpackTotalItem)
        {
            if (item.isHide)
            {
              
                handleInFind(item);
                item.gameObject.SetActive(false);
                //yield return new WaitForSeconds(item.hideLoadNum);
                yield return new WaitForSeconds(1);

                InventoryInFind.show(false);
                item.gameObject.SetActive(true);
                item.setIsHide(false);
            }

        }

    }

    private void InsertItem(InventoryItem itemInsert)
    {
        if (findGrid == null ) { return; }
        Vector2Int? posOnGrid = findGrid.FindSpaceForObject(itemInsert);
        if (posOnGrid ==null) {
            return;
        }

        findGrid.placeItem(itemInsert,posOnGrid.Value.x,posOnGrid.Value.y);
    }

    //private void swapInsertItem(ItemGrid itemGrid, InventoryItem itemInsert)
    //{
    //    if (itemGrid == null) { return; }
    //    Vector2Int? psoOnGrid = findGrid.FindSpaceForObject(itemInsert);
    //    if (psoOnGrid == null)
    //    {
    //        return;
    //    }

    //    itemGrid.placeItem(itemInsert, psoOnGrid.Value.x, psoOnGrid.Value.y);
    //}

    InventoryItem itemToHeight;
    private void handleHightLight()
    {
        Vector2Int positionOnGrid = GetTileGridPosition();
        if (oldPosition == positionOnGrid) { return; }

        oldPosition = positionOnGrid;
        if (selectedItem == null)
        {
            itemToHeight = selectedItemGrid.getItem(positionOnGrid.x,positionOnGrid.y);

            if (itemToHeight != null)
            {
                inventoryHeightLight.show(true);
                inventoryHeightLight.setSize(itemToHeight, selectedItemGrid);
                inventoryHeightLight.setParent(selectedItemGrid);
                inventoryHeightLight.SetPosition(selectedItemGrid, itemToHeight);
            }
            else {
                inventoryHeightLight.show(false);
            }
        }
        else {
            inventoryHeightLight.show(selectedItemGrid.BoundryCheck(positionOnGrid.x,positionOnGrid.y,selectedItem.WIDTH,selectedItem.HEIGHT));
            inventoryHeightLight.setSize(selectedItem, selectedItemGrid);
            inventoryHeightLight.setParent(selectedItemGrid);
            inventoryHeightLight.SetPosition(selectedItemGrid, selectedItem,positionOnGrid.x,positionOnGrid.y);
        }
    }

    private void handleInFind(InventoryItem item) {
        Vector2Int positionOnGrid = new Vector2Int(item.onGridPositionX,item.onGridPositionY);
        InventoryInFind.show(true);
        InventoryInFind.setSize(item, findGrid);
        InventoryInFind.setParent(findGrid);
        InventoryInFind.SetPosition(findGrid, item);
    }

    private void CreateRandomItem()
    {
      
        InventoryItem inventoryItem = Instantiate(itemPrefab).GetComponent<InventoryItem>();
        Guid uuid = Guid.NewGuid();
        inventoryItem.uuIdName = uuid.ToString();
        findItem = inventoryItem;
        findItem.needRaycast = false;

        //UnityAction<BaseEventData> pointerEnter = new UnityAction<BaseEventData>(selectedItem.PointerEnter);
        //EventTrigger.Entry enter = new EventTrigger.Entry();
        //enter.eventID = EventTriggerType.PointerEnter;
        //enter.callback.AddListener(pointerEnter);

        //UnityAction<BaseEventData> pointerExit = new UnityAction<BaseEventData>(selectedItem.PointerExit);
        //EventTrigger.Entry exit = new EventTrigger.Entry();
        //exit.eventID = EventTriggerType.PointerExit;
        //exit.callback.AddListener(pointerExit);

        //EventTrigger et=selectedItem.gameObject.AddComponent<EventTrigger>();
        //et.triggers.Add(enter);
        //et.triggers.Add(exit);


        rectTransform = inventoryItem.GetComponent<RectTransform>();
        rectTransform.SetParent(canvasTransForm);

        int selectItemId = UnityEngine.Random.Range(0,itemDatas.Count);

        ItemData itemdata = itemDatas[selectItemId];
        inventoryItem.set(itemdata,findGrid);
        
    }

    //private void leftButtonPress()
    //{
    //    if (selectedItemGrid == null) {
    //        return;
    //    }
    //    Vector2Int tileGridPostion = GetTileGridPosition();
    //    InventoryItem clickItem = selectedItemGrid.getItem(tileGridPostion.x, tileGridPostion.y);
    //    if (clickItem == null) { return; }
    //    if (clickItem.canShowDetail) {
    //        string name = clickItem.itemData.productName;
    //        int price = clickItem.itemData.price;
    //        string describe = clickItem.itemData.describe;

    //        GameObject allText = GameObject.FindGameObjectWithTag("gridText");
    //        UnityEngine.Vector2 mousePostion = Input.mousePosition;
    //        mousePostion = mousePostion - new UnityEngine.Vector2(-60, 50);
    //        allText.GetComponent<RectTransform>().position = mousePostion;

    //        Text[] text = allText.GetComponentsInChildren<Text>();
    //        foreach (Text content in text)
    //        {
    //            if (content.name == "productName")
    //            {
    //                content.text = name;
    //            }
    //            if (content.name == "productDetail")
    //            {
    //                content.text = describe;
    //            }
    //            if (content.name == "productPrice")
    //            {
    //                content.text = price + "";
    //            }
    //        }
    //    }
    //    //if (selectedItemGrid == null) {
    //    //    return;
    //    //}
    //    //Vector2Int tileGridPostion = GetTileGridPosition();

    //    //if (selectedItem == null)
    //    //{
    //    //    PickUpItem(tileGridPostion);
    //    //}
    //    //else
    //    //{
    //    //    PlaceItem(tileGridPostion);
    //    //}
    //}

    private Vector2Int GetTileGridPosition()
    {
        UnityEngine.Vector2 position = Input.mousePosition;

        if (selectedItem != null)
        {
            position.x -= (selectedItem.WIDTH - 1) * selectedItemGrid.tileSizeWidth / 2;
            position.y += (selectedItem.HEIGHT - 1) * selectedItemGrid.tileSizeHeight / 2;
        }

        return selectedItemGrid.GetTileGridPosition(position);
    }

    //private void iconDrog()
    //{
    //    if (selectedItem != null)
    //    {
    //        rectTransform.position = Input.mousePosition;
    //    }
    //}

    //private void PlaceItem(Vector2Int tileGridPosition) {
        
    //    Boolean isBound = selectedItemGrid.BoundryCheck(tileGridPosition.x, tileGridPosition.y, selectedItem.WIDTH, selectedItem.HEIGHT);
    //    if (!isBound) {
    //        return;
    //    }

    //    bool iscanPlace = selectedItemGrid.judgeCanPlace(tileGridPosition.x, tileGridPosition.y, selectedItem);
        
    //    if (!iscanPlace) {
    //        return;
    //    }
    //    List<ToSwapInventoryItem> swapInventoryItems = selectedItemGrid.getToSwapInventoryItemsAndClean(tileGridPosition.x, tileGridPosition.y, selectedItem,true);
    //    selectedItemGrid.placeItem(selectedItem,tileGridPosition.x, tileGridPosition.y);
    //    ItemGrid swapGrid = selectedItem.lastItemGrid;
    //    swapGrid.handleSwap(selectedItem.lastItemPosition, swapInventoryItems);
    //    selectedItem = null;
    //    //InventoryItem[,] swapInventoryItemSolt = selectedItemGrid.placeItem(selectedItem, tileGridPosition.x, tileGridPosition.y, ref overlapItem);
    //    //InventoryItem[,] swapInventoryItemSolt = selectedItemGrid.getSwap(tileGridPosition.x, tileGridPosition.y, selectedItem.WIDTH,selectedItem.HEIGHT);
    //    //selectedItemGrid.CleanGridReference(tileGridPosition.x, tileGridPosition.y, selectedItem.WIDTH, selectedItem.HEIGHT);
    //    //selectedItem = null;
    //    //bool complete = selectedItemGrid.placeItem(selectedItem, tileGridPosition.x, tileGridPosition.y,ref overlapItem);
    //    //if (complete) {
    //    //    selectedItem = null;
    //    //    if (overlapItem != null) {
    //    //        selectedItem = overlapItem;
    //    //        selectedItem.needRaycast = false;
    //    //        overlapItem = null;
    //    //        rectTransform = selectedItem.GetComponent<RectTransform>();
    //    //        rectTransform.SetAsFirstSibling();
    //    //    }
    //    //}
    //}

    //private void PickUpItem(Vector2Int tileGridPosition) {
    //    selectedItem = selectedItemGrid.pickUpItem(tileGridPosition.x, tileGridPosition.y);
    //    if (selectedItem != null)
    //    {
    //        selectedItem.setLastItemGrid(selectedItemGrid);
    //        selectedItem.setLastItemPosition(selectedItem.onGridPositionX,selectedItem.onGridPositionY);
    //        rectTransform = selectedItem.GetComponent<RectTransform>();
    //    }
    //}
}
